<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package      App_Sample
 * @copyright    Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version      $Id: StreamWrapper.php 130 2011-03-18 03:10:02Z cheng.wei $
 */

/** Zend_Log_Writer_Stream */
require_once 'Zend/Log/Writer/Stream.php';

/**
 * @package      App_Sample
 * @copyright    Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version      $Id: StreamWrapper.php 130 2011-03-18 03:10:02Z cheng.wei $
 */
class Zend_Log_Writer_StreamWrapper extends Zend_Log_Writer_Stream {
	
	/**
	 * Class Constructor
	 *
	 * @param  streamOrUrl     StreamWrapper or URL to open as a stream
	 * @param  mode            Mode, only applicable if a URL is given
	 */
	public function __construct($streamOrUrl, $mode = NULL, $limit = null) {
		// Setting the default
		if ($mode === NULL) {
			$mode = 'a';
		}
		
		if (is_string($streamOrUrl) && $limit) {
			
			if (is_file($streamOrUrl)) {
				$fsize = filesize($streamOrUrl);
				if ($fsize > $limit) {
					$fctime = filectime($streamOrUrl);
					$fltime = time();
					$timerange = date('YmdHis', $fctime) . '-' . date('YmdHis', $fltime);
					
					$pos = strrpos($streamOrUrl, '.');
					if ($pos) {
						$bkfile = substr($streamOrUrl, 0, $pos) . '-' . $timerange . substr(
							$streamOrUrl, $pos);
					} else {
						$bkfile = $streamOrUrl . '-' . $timerange;
					}
					rename($streamOrUrl, $bkfile);
				}
			}
			
			if (!$this->_stream = @fopen($streamOrUrl, $mode, false)) {
				require_once 'Zend/Log/Exception.php';
				$msg = "\"$streamOrUrl\" cannot be opened with mode \"$mode\"";
				throw new Zend_Log_Exception($msg);
			}
			
			$this->_formatter = new Zend_Log_Formatter_Simple();
			
			return;
		}
		parent::__construct($streamOrUrl, $mode);
	
	}
	
	/**
	 * Create a new instance of Zend_Log_Writer_Mock
	 * 
	 * @param  array|Zend_Config $config
	 * @return Zend_Log_Writer_Mock
	 * @throws Zend_Log_Exception
	 */
	static public function factory($config) {
		$config = self::_parseConfig($config);
		$config = array_merge(array('stream'=> null, 'mode'=> null, 'limit'=> 1024000), $config);
		
		$streamOrUrl = isset($config['url']) ? $config['url'] : $config['stream'];
		
		return new self($streamOrUrl, $config['mode'], $config['limit']);
	}

}
